package com.zyw.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.zyw.utils.PropertyHolder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author zhangyw
 * @date 2017/12/15 10:35
 */
@EnableTransactionManagement
public class DataSourceConfiguration {

    @Bean(name = "dataSource", initMethod = "init", destroyMethod = "close")
    public DruidDataSource configDS() {
        DruidDataSource ds = new DruidDataSource();
        ds.setUsername(PropertyHolder.getString("jdbc.username"));
        ds.setPassword(PropertyHolder.getString("jdbc.password"));
        ds.setUrl(PropertyHolder.getString("jdbc.url"));
        return ds;
    }

    @Bean(name = "jdbcTemplate")
    @ConditionalOnBean(DataSource.class)
    public JdbcTemplate configJdbcTemplate(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.setFetchSize(PropertyHolder.getInt("jdbc.fetchSize", 2000));
        return jdbcTemplate;
    }

    @Bean
    public DataSourceTransactionManager configDTM(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
